//
//  SecondViewController.m
//  SweetComics
//
//  Created by dlios on 15-1-29.
//  Copyright (c) 2015年 LeeZhe. All rights reserved.
//

#import "SecondViewController.h"
#import "ComicList.h"
#import "ComicsListCell.h"
#import "DetailViewController.h"
#import "MJRefresh.h"
#import "MJRefreshBaseView.h"
#import "MJRefreshConst.h"
#import "MJRefreshHeaderView.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD.h"
@interface SecondViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)MBProgressHUD *progress;
@end

@implementation SecondViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    //数组的初始化
    self.arr = [NSMutableArray array];
    
    self.temp = 2;
    [self createView];
    [self netWork];
    [self head];
    
   
    //去掉中间的横线
    //self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}

- (void)creatProgress
{
    self.progress = [[[MBProgressHUD alloc]initWithView:self.view]autorelease];
    self.progress.labelText = @"努力加载中";
    self.progress.labelFont = [UIFont systemFontOfSize:10];
    [self.progress show:YES];
    [self.view addSubview:self.progress];
}

- (void)createView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:_tableView];
//    [self.view setPreservesSuperviewLayoutMargins:NO];
//    [self.view setShouldGroupAccessibilityChildren:NO];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.title = @"漫画列表";
}

- (void)netWork
{
    [self creatProgress];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager GET:kComicsList parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dic = responseObject;
        NSMutableArray *comicArr = [dic objectForKey:@"data"];
        for (NSDictionary *dic in comicArr) {
            ComicList *comics = [[ComicList alloc]init];
            [comics setValuesForKeysWithDictionary:dic];
            [self.arr addObject:comics];
            //NSLog(@"%@", comics);
            [comics release];
            [self.progress hide:YES afterDelay:1];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
}


- (void)head
{
    [self.tableView addHeaderWithTarget:self action:@selector(headRefresh)];
    [self.tableView addFooterWithTarget:self action:@selector(footRefresh)];
    self.tableView.headerPullToRefreshText = @"下拉刷新啦";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新啦";
    self.tableView.headerRefreshingText = @"正在刷新中, 请稍后啊";
    
    self.tableView.footerPullToRefreshText = @"上拉加载更多数据啦";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据啦";
    self.tableView.footerRefreshingText = @"正在加载中, 不客气";
}

//下拉刷新
- (void)headRefresh
{
    //自动刷新
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     //刷新表格
      [self.tableView reloadData];
      //让下拉刷新头部控件停止帅新状态
      [self.tableView headerEndRefreshing];
      
  });
}

//上拉加载
- (void)footRefresh
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString *strUrl = [NSString stringWithFormat:@"%ld", (long)self.temp];
        NSString *str = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Classify/categoryList/category_id/50005/listcnt/13/page/%@1/clientType/0",strUrl];
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        [manager GET:str parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSMutableDictionary *dic = responseObject;
            NSMutableArray *comicArr = [dic objectForKey:@"data"];
            for (NSDictionary *dic in comicArr) {
                ComicList *comics = [[ComicList alloc]init];
                [comics setValuesForKeysWithDictionary:dic];
                [self.arr addObject:comics];
  //              NSLog(@"%@", comics);
            }
            [self.tableView reloadData];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@", error);
        }];
        //让上拉刷新尾部的部件停止刷新
        [self.tableView footerEndRefreshing];
        self.temp += 1;
    });
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ComicList *comics = [self.arr objectAtIndex:indexPath.row];
    DetailViewController *detail = [[DetailViewController alloc]init];
    detail.comic = comics;
    [self.navigationController pushViewController:detail animated:YES];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"123";
    ComicsListCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[ComicsListCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str]autorelease];
    }
    
    ComicList *comic = [self.arr objectAtIndex:indexPath.row];
    
    //调用这个方法
    [cell setComics:comic];
    return cell;
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}












- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
